//
//  YYYLabel.swift
//  HotNews
//
//  Created by YYY on 2017/11/6.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import UIKit

class YYYLabel: UILabel {

    //文本存储
    private lazy var textStorage = NSTextStorage()
    //文本字形布局
    private lazy var textLayout = NSLayoutManager()
    //文本绘制的范围
    private lazy var textContainer = NSTextContainer()
    
    override var text: String?
    {
        didSet
        {
            //准备文本内容
            prepareTextContent()
        }
    }
    init(frame: CGRect, textStr: String) {
        super.init(frame: frame)
        //打开交互
        isUserInteractionEnabled = true
        text = textStr
        //准备文本系统
        prepareTextSystem()
    }
    
    override func layoutSubviews()
    {
        super.layoutSubviews()
        textContainer.size = bounds.size
    }
    
    override func drawText(in rect: CGRect)
    {
        let range = NSRange(location: 0, length: textStorage.length)
        //设置背景颜色
        textLayout.drawBackground(forGlyphRange: range, at: CGPoint())
        textLayout.drawGlyphs(forGlyphRange: range, at: CGPoint())
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("点击事件")
        guard let location = touches.first?.location(in: self) else
        {
            return
        }
        let index = textLayout.glyphIndex(for: location, in: textContainer)
        print(index)
        for range in urlRanges ?? []
        {
            if NSLocationInRange(index, range)
            {
                textStorage.addAttributes([NSAttributedStringKey.foregroundColor: UIColor.yellow], range: range)
                print("需要高亮")
                
                setNeedsDisplay()
            }
            else
            {
                print("不需要高亮")
            }
        }
    }
}

private extension YYYLabel
{
    //准备文本系统
    func prepareTextSystem()
    {
        //准备文本内容
        prepareTextContent()
        //设置对象之间的关系
        textStorage.addLayoutManager(textLayout)
        textLayout.addTextContainer(textContainer)
    }
    
    //准备文本内容
    func prepareTextContent()
    {
        if let attributedText = attributedText
        {
            textStorage.setAttributedString(attributedText)
        }
        else if let text = text
        {
            textStorage.setAttributedString(NSAttributedString(string: text))
        }
        else
        {
            textStorage.setAttributedString(NSAttributedString(string: ""))
        }

        for range in urlRanges ?? []
        {
            //设置URL的字体颜色
            textStorage.addAttributes([NSAttributedStringKey.foregroundColor: UIColor.blue,
                                       NSAttributedStringKey.backgroundColor: UIColor.lightGray], range: range)
            
            
        }
    }
}

private extension YYYLabel
{
    var urlRanges: [NSRange]?
    {
        let pattern = "[a-zA-Z]*://[a-zA-Z0-9/\\.]*"
        
        //创建正则表达式
        guard let regx = try? NSRegularExpression(pattern: pattern, options: []) else
        {
            return nil
        }
        let matches = regx.matches(in: textStorage.string, options: [], range: NSRange(location: 0, length: textStorage.length))
        
        var ranges = [NSRange]()
        for m in matches
        {
            let range = m.range(at: 0)
            ranges.append(range)
        }
        return ranges
    }
    
}
